﻿using Forum.Infrastructure;
using Forum.Model.Entity;
using Forum.Model.Enum;
using Forum.Model.Pager;
using Forum.Model.QueryFilters;
using Forum.Model.Request;
using Forum.Model.Response;
using Forum.Repository.Extensions;
using Forum.Repository.Interface;
using Forum.Service.Interface;
using Microsoft.AspNetCore.SignalR;
using Forum.Model;
using Forum.Service.ForumHub;
using Forum.Model.Entity.System;

namespace Forum.Service.Service
{
    public class BasicService : IBasicService
    {
        private readonly IAppRepository<Site> _siteRepo;
        private readonly IAppRepository<Social> _socialRepo;
        private readonly IAppRepository<Link> _linkRepo;
        private readonly IAppRepository<SysParameters> _paramRepo;
        private readonly IAppRepository<Notice> _noticeRepo;
        private readonly IAppRepository<User> _userRepo;
        private readonly IHubContext<ServerHub> _hubContext;
        public BasicService(IAppRepository<Site> siteRepo,
            IAppRepository<Social> socialRepo,
            IAppRepository<Link> linkRepo,
            IAppRepository<SysParameters> paramRepo,
            IAppRepository<Notice> noticeRepo,
            IAppRepository<User> userRepo,
            IHubContext<ServerHub> hubContext)
        {
            _siteRepo = siteRepo;
            _socialRepo = socialRepo;
            _linkRepo = linkRepo;
            _paramRepo = paramRepo;
            _noticeRepo = noticeRepo;
            _userRepo = userRepo;
            _hubContext = hubContext;
        }

        public Site GetSiteInfo()
        {
            return _siteRepo.GetList().First();
        }

        public async Task<bool> UpdateSiteInfo(Site site)
        {
            var Msg = $"{CurrentUser.UserName}修改了网站信息";
            //将消息写入通知表
            var users = _userRepo.GetList(a => a.IsAdmin);
            if (users != null)
            {
                foreach (var user in users)
                {
                    Notice notice = new Notice();
                    notice.Msg = Msg;
                    notice.PublishDate = DateTime.Now;
                    notice.UserId = user.UserId;
                    _noticeRepo.Insert(notice);
                }
            }

            await _hubContext.Clients.All.SendAsync("SiteMsg", Msg);
            return _siteRepo.Update(site);
        }


        public List<Social> GetSocialList()
        {

            return _socialRepo.GetList();
        }

        /// <summary>
        /// 查询所有已审核完成的友链
        /// </summary>
        /// <returns></returns>
        public List<Link> GetLinkList()
        {
            return _linkRepo.GetList(a => a.Visible);
        }

        /// <summary>
        /// 插入友链数据
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public ApiResponse AddLink(LinkReq req)
        {
            var link = req.MapTo<LinkReq, Link>();
            link.Id = Guid.NewGuid().ToString("N");
            link.Visible = false;
            var result = _linkRepo.InsertRemoveCache(link);

            return result ? ApiResponse.OK() : ApiResponse.Error("提交异常");
        }

        /// <summary>
        /// 分页查询友链
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public IPagedList<Link> GetLinkPagedList(QueryParameters param)
        {
            var querySet = _linkRepo.SugarQueryable;

            // 关键词过滤
            if (!string.IsNullOrEmpty(param.Search))
            {
                querySet = querySet.Where(a => a.Name.Contains(param.Search));
            }
            // 排序
            if (!string.IsNullOrEmpty(param.SortBy))
            {
                // 是否升序
                var ascending = !param.SortBy.StartsWith("-") ? " asc" : " desc";
                var orderByProperty = param.SortBy.Trim('-');

                querySet = querySet.OrderBy(orderByProperty + ascending);
            }

            return querySet.ToPage(param.Page, param.PageSize);
        }

        /// <summary>
        /// 更新友链
        /// </summary>
        /// <param name="id"></param>
        /// <param name="visible"></param>
        /// <returns></returns>
        public bool UpdateLink(string id, bool visible)
        {
            var link = _linkRepo.FindEntity(a => a.Id == id);
            if (link == null)
                return false;
            link.Visible = visible;
            return _linkRepo.Update(link);
        }

        /// <summary>
        /// 删除友链
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteLink(string id)
        {
            var link = _linkRepo.FindEntity(a => a.Id == id);
            if (link == null)
                return false;
            return _linkRepo.Delete(link);
        }

        /// <summary>
        /// 系统参数查询
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public IPagedList<SysParameters> GetParamPagedList(QueryParameters param)
        {
            var querySet = _paramRepo.SugarQueryable;

            // 关键词过滤
            if (!string.IsNullOrEmpty(param.Search))
            {
                querySet = querySet.Where(a => a.Key.Contains(param.Search));
            }
            // 排序
            if (!string.IsNullOrEmpty(param.SortBy))
            {
                // 是否升序
                var ascending = !param.SortBy.StartsWith("-") ? " asc" : " desc";
                var orderByProperty = param.SortBy.Trim('-');

                querySet = querySet.OrderBy(orderByProperty + ascending);
            }

            return querySet.ToPage(param.Page, param.PageSize);
        }

        /// <summary>
        /// 查询单条信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public SysParameters GetByParamId(string id)
        {
            return _paramRepo.FindEntity(a => a.Id == id);
        }

        /// <summary>
        /// 删除系统参数
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteParam(string id)
        {
            return _paramRepo.Delete(a => a.Id == id);
        }

        public bool AddParam(ParamsReq req)
        {
            var param = req.MapTo<ParamsReq, SysParameters>();
            param.Id = Guid.NewGuid().ToString();
            param.CreationTime = DateTime.Now;
            param.Status = (int)StatusEnum.可用;
            return _paramRepo.Insert(param);
        }

        public bool UpdateParam(SysParameters req)
        {
            return _paramRepo.Update(req);
        }
    }
}
